const express=require('express');
const static=require('express-static');
const bodyParser=require('body-parser');
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session');
const fs=require('fs');
const pathLib=require('path');
const multer=require('multer');
const consolidate=require('consolidate');
const ejs=require('ejs');
const mysql=require('mysql');
const crypto=require('crypto');

const common=require('./libs/common');

var db=mysql.createPool({
    host:'localhost',
    port:'3306',
    user:'root',
    password:'123456',
    database:'boke'
});



var server=express();
server.listen(8080);

//解析cookie、session
var cookieKeys=[];
for(var i=0;i<1000;i++){
    cookieKeys[i]='a_'+Math.random();
}
server.use(cookieParser());
server.use(cookieSession({
    name:'see_id',
    keys:cookieKeys,
    maxAge:24*3600*1000
}))
//解析post数据、上传文件
server.use(bodyParser.urlencoded({extended:false}))
var objMulter=multer({dest:'./www/uploade/'});
server.use(objMulter.any());

//模板ejs
server.set('view engine','html');
server.set('views','./template');
server.engine('html',consolidate.ejs);

//解析web页面
server.get('/',(req,res)=>{
    res.send('web');
});
//解析boss页面
server.get('/admin/',(req,res)=>{
    if(!req.session['admin_id']&&req.url!='/admin/login'){
        res.redirect('/admin/login');
    }else{
        res.render('./admin/index.ejs',{})
    }
});
//boss登录
server.get('/admin/login',(req,res)=>{
    res.render('./admin/login.ejs',{});
})
server.post('/admin/login',(req,res)=>{
    var username=req.body.name;
    var password=common.md5(req.body.pass+common.MD5HEX);
    db.query(`SELECT * FROM admin_table WHERE username='${username}'`,function(err,data){
        if(err){
            console.log('查询失败。')
        }else{
            if(data.length==0){
                res.send('该用户管理不存在').end();
            }else{
                if(data[0].password==password){
                    // res.status(200).send('登录成功').end();
                    req.session['admin_id']=data[0].ID;
                    res.redirect('/admin/');
                }else{
                    res.status(200).send('密码输入有误').end();
                }
            }
        }  
    })
})

//解析静态文件
server.use(static('./www'));